﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using NPOI.XSSF.UserModel;
namespace AutoWelding.Utils
{
    public class ExcelUtils
    {
        /// <summary>
        /// 导出DataGridView数据到Excel
        /// </summary>
        /// <param name="myDGV"></param>
        public static void ExportToExcel(DataGridView myDGV)
        {
            SaveFileDialog saveDialog = new SaveFileDialog();
            saveDialog.Title = "请选择要导出的位置";
            saveDialog.Filter = "Excel文件|*.xlsx";
            if (saveDialog.ShowDialog() != DialogResult.OK) return;

            string path = saveDialog.FileName;
            if (string.IsNullOrEmpty(path)) return;

            try
            {
                using (var workbook = new XSSFWorkbook()) // 创建 .xlsx 工作簿
                using (var fs = new FileStream(path, FileMode.Create, FileAccess.Write))
                {
                    var sheet = workbook.CreateSheet("日志数据");

                    // 写入标题行
                    var headerRow = sheet.CreateRow(0);
                    for (int i = 0; i < myDGV.Columns.Count; i++)
                    {
                        if (myDGV.Columns[i].Visible)
                        {
                            var cell = headerRow.CreateCell(i);
                            cell.SetCellValue(myDGV.Columns[i].HeaderText);
                        }
                    }

                    // 写入数据行
                    for (int i = 0; i < myDGV.Rows.Count; i++)
                    {
                        var dataRow = sheet.CreateRow(i + 1);

                        for (int j = 0; j < myDGV.Columns.Count; j++)
                        {
                            if (myDGV.Columns[j].Visible)
                            {
                                var value = myDGV.Rows[i].Cells[j].Value?.ToString() ?? "";
                                dataRow.CreateCell(j).SetCellValue(value);
                            }
                        }
                    }

                    // 自动调整列宽（基于内容）
                    for (int i = 0; i < myDGV.Columns.Count; i++)
                    {
                        if (myDGV.Columns[i].Visible)
                        {
                            sheet.AutoSizeColumn(i); // 自动调整列宽
                        }
                    }

                    workbook.Write(fs);
                }

                MessageBox.Show("成功导出到" + path);
            }
            catch (Exception ex)
            {
                MessageBox.Show("导出失败：" + ex.Message, "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
    }
}
